<div id="formDiv"></div>
<style>
  #purchaseOrderForm .layui-form-label {
    width: 110px;
  }

  #purchaseOrderForm .layui-input-block {
    margin-left: 140px;
  }
</style>
<script type="text/html" id="formContent">
  <form lay-filter="purchaseOrderForm" id="purchaseOrderForm" class="layui-form open-form">
    <div class="open-model" id="purchaseOrderFormContent">
      <div class="open-auto">
        <div class="layui-form-item layui-row">
          <input name="id" type="hidden" />
          <input name="purchaseQuotationId" type="hidden" />
          <div class="layui-col-xs3">
            <label class="layui-form-label">采购类型<span style="color:red;">*</span></label>
            <div class="layui-input-block">
              <select id="purchaseType" name="purchaseType" lay-filter="purchaseType" lay-verify="required" required></select>
            </div>
          </div>
          <div class="layui-col-xs3">
            <label class="layui-form-label">紧急程度<span style="color:red;">*</span></label>
            <div class="layui-input-block">
              <select id="emergencyDegree" name="emergencyDegree" lay-verify="required" required></select>
            </div>
          </div>
          <div class="layui-col-xs3">
            <label class="layui-form-label">供应商<span style="color:red;">*</span></label>
            <div class="layui-input-block">
              <select id="supplierId" name="supplierId" lay-filter="supplierId" class="common-select-search" lay-search=""></select>
            </div>
          </div>
          <div class="layui-col-xs3">
            <label class="layui-form-label">供应商联系人</label>
            <div class="layui-input-block">
              <select id="businessContact" name="businessContact" lay-search=""></select>
            </div>
          </div>
        </div>
        <div class="layui-form-item layui-row">
          <div class="layui-col-xs3" style="margin-top: 10px;">
            <label class="layui-form-label">审核部门</label>
            <div class="layui-input-block">
              <input name="departmentName" id="departmentName" class="layui-input" disabled />
            </div>
            <input name="departmentId" id="departmentId" class="layui-input" type="hidden" />
            <!--<div class="layui-input-block" id="selectDepartment" disabled="true"></div>-->
          </div>
          <div class="layui-col-xs3" style="margin-top: 10px;">
            <label class="layui-form-label">审核岗位</label>
            <div class="layui-input-block">
              <input name="postName" id="postName" class="layui-input" disabled />
            </div>
          </div>
          <div class="layui-col-xs3" style="margin-top: 10px;">
            <label class="layui-form-label">是否已签约</label>
            <div class="layui-input-block">
              <select name="hasSign" lay-filter="hasSign">
                <option value="">请选择是否签约</option>
                <option value="1">已签约</option>
                <option value="0">未签约</option>
              </select>
            </div>
          </div>
          <div class="layui-col-xs3" style="margin-top: 10px;" id="contractIdSelect">
            <label class="layui-form-label">选择合同</label>
            <div class="layui-input-block">
              <select name="contractId" id="contractId" lay-filter="contractId"></select>
            </div>
          </div>
          <div class="layui-col-xs3" style="margin-top: 10px;">
            <label class="layui-form-label">预计交付时间</label>
            <div class="layui-input-block">
              <input name="planDeliverTime" id="planDeliverTime" class="layui-input" />
            </div>
          </div>

          <div class="layui-col-xs3" style="margin-top: 10px;">
            <label class="layui-form-label">录入时间</label>
            <div class="layui-input-block">
              <input name="enterTime" id="enterTime" class="layui-input" />
            </div>
          </div>
        </div>
        <div class="layui-form-item tableContent">
          <!-- {{# if(d.eventName==='edit'||(d.eventName==='add'&&!d.data)){ }} -->
          <button class="layui-btn" type="button" id="Configure">配置请购物资</button>
          <!-- {{# } }} -->
          <table class="layui-table" id="purchaseOrderFormTable" lay-filter="purchaseOrderFormTable"></table>
        </div>
      </div>
      <div class="layui-form-item text-right">
        <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">关闭</button>
        <!-- {{# if(!['acceptance','view'].includes(d.eventName)){ }} -->
        <button class="layui-btn" lay-filter="inquiryOrderInformationSubmit" type="button" lay-submit>提交</button>
        <!-- {{# } }} -->
      </div>
    </div>
  </form>
</script>
<script type="text/html" id="purchaseOrderFormTableBar">
  <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" type="button">删除</button>
</script>
<script>
  layui.use(["layer", "form", "table", "admin", "laydate", "upload", "laytpl"], async function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var config = layui.config;
    var admin = layui.admin;
    var upload = layui.upload;
    let laydate = layui.laydate;
    let laytpl = layui.laytpl;
    const nowData = { ...parentData };
    let data = nowData.data;
    console.log("data", nowData);

    // const loadingIndex = layer.load();
    laytpl(formContent.innerHTML).render({ ...nowData }, function (html) {
      $("#formDiv").after(html);
    });
    $("#contractIdSelect").hide();
    laydate.render({
      elem: "#enterTime",
      type: "datetime"
    });
    laydate.render({
      elem: "#planDeliverTime",
      type: "datetime"
    });
    if (nowData.eventName === "view") {
      admin.setFormDisable("#purchaseOrderFormContent", true);
    }

    await admin.initDataSelectPro(
      "enterprise/purchase/admin/purchaseType/list",
      {},
      "purchaseType",
      "采购类型",
      async (d, obj) => {
        form.val("purchaseOrderForm", {
          departmentName: "",
          departmentId: "",
          postName: ""
        });
        $("#auditor").empty();
        if (obj) {
          form.val("purchaseOrderForm", {
            departmentName: obj.department,
            departmentId: obj.departmentId,
            postName: obj.stations
          });
          await admin.initDataSelectPro("user/admin/user/list", { postId: obj.stationsId }, "auditor", "订单审核人", null, "nickname");
        }
        form.render("select");
      },
      "purchaseTypeName"
    );
    await admin.initDataSelectPro("enterprise/purchase/admin/purchaseUrgency/list", {}, "emergencyDegree", "紧急程度", null, "purchaseUrgencyName");
    await admin.initDataSelectPro(
      "enterprise/purchase/admin/supplierInfoPass/list",
      { limit: 9999 },
      "supplierId",
      "供应商",
      async (d, obj) => {
        $("#businessContact").empty();
        form.val({
          businessContact: ""
        });
        if (d.value) {
          //供应商联系人列表
          const businessContactRes = await admin.initDataSelectPro(
            "enterprise/purchase/admin/supplierContacts/list",
            {
              limit: 9999,
              corporateId: d.value
            },
            "businessContact",
            "供应商联系人",
            null,
            "contactName"
          );
          form.val("purchaseOrderForm", {
            businessContact: businessContactRes.length > 0 ? businessContactRes[0].id : ""
          });
        }
      },
      "corporateName"
    );

    form.on("select(hasSign)", async function (data) {
      if (data.value == 1) {
        $("#contractIdSelect").show();
        $("#contractId").empty();
        // 选择合同
        await admin.initDataSelectPro("enterprise/purchase/admin/supplierContract/list", { status: 1 }, "contractId", "合同");
      } else {
        $("#contractId").empty();
        // 选择合同
        await admin.initDataSelectPro("enterprise/purchase/admin/supplierContract/list", { status: 1 }, "contractId", "合同");
        $("#contractIdSelect").hide();
      }
    });
    // Add debounce function at the beginning
    if(nowData.eventName === "addPlan"){
      initSkuTable([nowData.productDetailId]);
    }
    function debounce(func, wait, immediate) {
      let timeout;
      return function () {
        const context = this,
          args = arguments;
        const later = function () {
          timeout = null;
          if (!immediate) func.apply(context, args);
        };
        const callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
      };
    }

    // Flags to track input status
    let isInputtingPrice = false;
    let isInputtingTaxPrice = false;
    table.render({
      elem: "#purchaseOrderFormTable",
      limit: 999999,
      page: false,

      data: [],
      cols: [
        [
          { type: "numbers", title: "序号", fixed: "left" },
          { field: "productName", align: "center", title: "物料名称" },
          { field: "skuCode", align: "center", title: "物料编号" },
          { field: "specifications", align: "center", title: "规格型号" },
          // {field: 'productTypeName', align: 'center', title: "物料类型"},
          { field: "haveQuantity", align: "center", title: "当前库存数" },
          {
            field: "needQuantity",
            align: "center",
            title: "需求数量",
            hide: nowData.eventName === "edit" || (nowData.eventName === "add" && !nowData.data) || nowData.eventName === "addPlan"
          },
          {
            field: "surplusQuantity",
            align: "center",
            title: "剩余采购数量",
            hide: nowData.eventName === "edit" || (nowData.eventName === "add" && !nowData.data) || nowData.eventName === "addPlan"
            // templet: function (d) {
            //     let needQuantity = Number(d.needQuantity)
            //     let hasDeliveryQuantity = Number(d.hasDeliveryQuantity)
            //     if (needQuantity && hasDeliveryQuantity) {
            //         return needQuantity - hasDeliveryQuantity
            //
            //     } else {
            //         return 0
            //     }
            // }
          },
          { field: "unitName", align: "center", title: "采购单位" },
          {
            field: "quantity",
            align: "center",
            title: "数量",
            templet: admin.setTableInput("quantity", nowData.eventName === "view", "quantity")
          },
          { field: "taxPrice", align: "center", title: "参考成本" },

          {
            field: "rate",
            align: "center",
            title: "税率(%)",
            templet: admin.setTableInput("rate", nowData.eventName === "view", "rate")
          },
          {
            field: "price",
            align: "center",
            title: "单价",
            templet: admin.setTableInput("price", nowData.eventName === "view", "price")
          },
          {
            field: "taxPrice",
            align: "center",
            title: "含税单价",
            templet: admin.setTableInput("taxPrice", nowData.eventName === "view", "taxPrice")
          },
          { field: "tax", align: "center", title: "税额" },

          { field: "amount", align: "amount", title: "不含税金额" },
          {
            field: "totalAmount",
            align: "center",
            title: "含税金额"
          },
          {
            field: "remark",
            align: "center",
            title: "备注",
            templet: admin.setTableInput("remark", nowData.eventName === "view", "remark")
          },
          {
            align: "center",
            fixed: "right",
            toolbar: "#purchaseOrderFormTableBar",
            title: "操作",
            hide: nowData.eventName === "view" || nowData.eventName === "addPlan"
          }
        ]
      ],
      done: function () {
        const debouncedReload = debounce(function (tableData) {
          if (!isInputtingPrice && !isInputtingTaxPrice) {
            table.reload("purchaseOrderFormTable", {
              data: tableData
            });
          }
        }, 600);
        // 计算方法
        function calculate(index, tableData, type) {
          let quantity = Number(tableData[index].quantity || 0); // 数量
          let rate = Number(tableData[index].rate || 0) / 100; // 税率
          let price = Number(tableData[index].price || 0); // 不含税单价
          let taxPrice = Number(tableData[index].taxPrice || 0); // 含税单价
          if (type === "price") {
            taxPrice = (price * (1 + rate)).toFixed(6); // 含税单价
          } else {
            price = (taxPrice / (1 + rate)).toFixed(6); // 不含税单价
          }
          let tax = (price * rate * Number(quantity)).toFixed(6); // 税额
          let totalAmount = (Number(taxPrice) * Number(quantity)).toFixed(6); // 含税金额
          let amount = (totalAmount - tax).toFixed(6); // 不含税金额

          tableData[index].amount = amount;
          tableData[index].tax = tax;
          tableData[index].taxPrice = taxPrice;
          tableData[index].totalAmount = totalAmount;
          tableData[index].price = price;

          admin.setTableColHtml("purchaseOrderFormTable", index, "amount", tableData[index].amount);
          admin.setTableColHtml("purchaseOrderFormTable", index, "tax", tableData[index].tax);

          setTimeout(() => {
            isInputtingPrice = false;
            isInputtingTaxPrice = false;
          }, 210);

          // Trigger debounced reload
          debouncedReload(tableData);

          admin.setTableColHtml("purchaseOrderFormTable", index, "totalAmount", tableData[index].totalAmount);
        }
        admin.tableInputChangeByClass("purchaseOrderFormTable", "remark", null);
        admin.tableInputChangeByClass("purchaseOrderFormTable", "rate", (index, value, tableData, field, tableId) => {
          calculate(index, tableData, "rate");
        });
        admin.tableInputChangeByClass("purchaseOrderFormTable", "price", (index, value, tableData, field, tableId) => {
          calculate(index, tableData, "price");
        });
        admin.tableInputChangeByClass("purchaseOrderFormTable", "taxPrice", (index, value, tableData, field, tableId) => {
          calculate(index, tableData, "taxPrice");
        });
        admin.tableInputChangeByClass("purchaseOrderFormTable", "quantity", (index, value, tableData, field, tableId) => {
          console.log("quantity", index, value, tableData, field, tableId);
          calculate(index, tableData, "quantity");
        });
      },
      error: function () {
        console.log("请求失败");
      }
    });
  
    async function initSkuTable(list) {
      const { data } = await admin.reqPro("enterprise/product/admin/productDetailWMS/list", {
        inIds: list.join(",")
      });
      var list = data.map((v) => {
        v.productCategory = v.productTypeId;
        v.productName = v.skuName;
        v.specifications = v.skuSpec;
        v.unitName = v.mainUnitName;
        v.remark = "";
        v.rate = v.taxRate === "" || !v.taxRate ? "0" : v.taxRate;
        v.taxPrice = v.currentCostPrice;
        return v;
      });
      window.setTimeout(() => {
        table.reload("purchaseOrderFormTable", { data: list });
      }, 100);
    }
   
    if (data && data.id) {
      await admin.initDataSelectPro(
        "enterprise/purchase/admin/supplierContacts/list",
        {
          limit: 9999,
          corporateId: data.supplierId
        },
        "businessContact",
        "供应商联系人",
        null,
        "contactName"
      );
      form.val("purchaseOrderForm", data);
      let list = data.list.map((v) => {
        v.amount = v.totalAmount - v.tax;
        return v;
      });

      table.reload("purchaseOrderFormTable", {
        data: list
      });
    }

    $("#Configure").click(function () {
      admin.formOpen({
        area: "90%",
        offset: "50px",
        title: "配置物料信息",
        path: "components/purchase/skuTableForm.html",
        success: function () {
          parentData.cacheList = [...table.cache["purchaseOrderFormTable"]];
          parentData.materialNatureList = ["1"];

          console.log(parentData.cacheList);
          if (parentData.cacheList.length > 0) {
            parentData.notInListIds = table.cache["purchaseOrderFormTable"]
              .map((v) => {
                // if (v.id) return v.id
                if (v.productDetailId) return v.productDetailId;
              })
              .join(",");
          } else {
            parentData.notInListIds = "";
          }
        },
        end: function () {
          if (childData.list) {
            const newData = childData.list || [];
            newData.forEach((v) => {
              v.productCategory = v.productTypeId;
              v.productName = v.skuName;
              v.specifications = v.skuSpec;
              v.unitName = v.mainUnitName;
              v.remark = "";
              v.rate = v.taxRate === "" || !v.taxRate ? "0" : v.taxRate;
              v.taxPrice = v.currentCostPrice;
            });
            const oldData = table.cache["purchaseOrderFormTable"];
            const list = [...oldData, ...newData];
            table.reload("purchaseOrderFormTable", {
              data: list // 设置新的数据
            });
          }
        }
      });
    });

    form.on("submit(inquiryOrderInformationSubmit)", function (d) {
      const formData = { ...d.field };
      formData.purchaseOrderDetails = table.cache["purchaseOrderFormTable"];
      console.log("formData", formData);
      if (nowData.eventName === "add"||nowData.eventName === "addPlan") {
        admin.req(
          "enterprise/purchase/admin/purchaseOrder/add",
          JSON.stringify(formData),
          function (data) {
            layer.closeAll("loading");
            if (data.code == 200) {
              layer.msg(data.msg, { icon: 1, time: 500 });
              table.reload("erpPurchaseOrder-table");
              layer.closeAll("page");
            } else {
              layer.msg(data.msg, { icon: 2, time: 1000 });
            }
          },
          "POST",
          false,
          "application/json"
        );
      } else if (nowData.eventName === "edit") {
        admin.req(
          "enterprise/purchase/admin/purchaseOrder/update",
          JSON.stringify(formData),
          function (data) {
            layer.closeAll("loading");
            if (data.code == 200) {
              layer.msg(data.msg, { icon: 1, time: 500 });
              table.reload("erpPurchaseOrder-table", {});
              layer.closeAll("page");
            } else {
              layer.msg(data.msg, { icon: 2, time: 1000 });
            }
          },
          "PUT",
          false,
          "application/json"
        );
      }
      // admin.req('enterprise/purchase/admin/purchasePlanCheck/addPurchaseRequisitions', JSON.stringify(formData), function (res) {
      //     layer.closeAll('loading');
      //     if (res.code == 200) {
      //         layer.msg(res.msg, {icon: 1, time: 500});
      //         table.reload('purchasePlanCheckTable');
      //         layer.closeAll('page');
      //     } else {
      //         layer.msg(res.msg, {icon: 2, time: 1000});
      //     }
      // }, 'POST', false, "application/json");
      return false;
    });

    table.on("tool(purchaseOrderFormTable)", function (obj) {
      var d = obj.data; // 获取当前行的数据
      var layEvent = obj.event; // 获取事件名（edit 或 del）
      if (obj.tr) {
        obj.tr.on("click", function (e) {
          e.preventDefault(); // 防止默认行为
        });
      }
      if (layEvent == "del") {
        const index = $(obj.tr[0]).data("index");
        let list = table.cache["purchaseOrderFormTable"].filter((v) => {
          return v["LAY_TABLE_INDEX"] != index;
        });
        table.reload("purchaseOrderFormTable", {
          data: list
        });
      }
    });
  });
</script>
